package com.fable.ntzw_ga.controller;


import cn.hutool.core.convert.Convert;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fable.common.eunm.AppHttpCodeEnum;
import com.fable.common.constants.CommonConstant;
import com.fable.common.vo.ResultVO;
import com.fable.common.dto.GuestDTO;
import com.fable.ntzw_ga.entity.FeastRecompense;
import com.fable.ntzw_ga.entity.FeastType;
import com.fable.ntzw_ga.entity.Guest;
import com.fable.ntzw_ga.service.IFeastRecompenseService;
import com.fable.ntzw_ga.service.IFeastTypeService;
import com.fable.ntzw_ga.service.IGuestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Created by gzh 2023-01-31 23:12:37
 */
@Api(tags = "宾客管理")
@RestController
@RequestMapping("/ntzw_ga/guest")
@PreAuthorize("hasRole('admin')")
@Slf4j
public class GuestController {


    @Autowired
    IGuestService guestService;

    @Autowired
    IFeastTypeService feastTypeService;

    @Autowired
    IFeastRecompenseService recompenseService;

    @ApiOperation(value = "搜索宾客信息")
    @PostMapping("getAll")
    public ResultVO getDataList(@RequestBody Map<String, Object> map) {
        Guest guest = new Guest();
        GuestDTO guestDTO = JSON.parseObject(JSON.toJSONString(map.get("filters")), GuestDTO.class);
        List<Map<String, Object>> collect = potoToDto(guest, guestDTO);
//        PageInfo<Map<String, Object>> guestPageInfo = PageInfoUtils.getPageInfo(Convert.toInt(map.get("pageNum")), Convert.toInt(map.get("pageSize")), collect);

        return ResultVO.okResult();
    }

    @ApiOperation(value = "获取单个宾客信息")
    @GetMapping("getOne/{id}")
    public ResultVO getOne(@PathVariable String id) {
        return ResultVO.okResult(guestService.getById(id));
    }

    @ApiOperation(value = "获取酒席类型")
    @GetMapping("getFeastTypeList")
    public ResultVO getFeastTypeList(){
        LambdaQueryWrapper<FeastType> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(FeastType::getRemarks,FeastType::getId).orderByDesc(FeastType::getFeastTime);
        List<FeastType> list = feastTypeService.list(wrapper);
        return ResultVO.okResult(list);
    }

    @ApiOperation(value = "添加宾客")
    @PostMapping("save")
    @Transactional
    public ResultVO saveGuestUser(@RequestBody Guest guest) {
        FeastType one = feastTypeService.getOne(new LambdaQueryWrapper<FeastType>().eq(FeastType::getFeastStatus, true));
        guest.setCreateTime(LocalDateTime.now());
        guest.setFeastTypeId(one.getId());
        guest.setRemarks(one.getRemarks());
        return guestService.save(guest) ? ResultVO.okResult() : ResultVO.errorResult(AppHttpCodeEnum.ERROR);
    }

    @ApiOperation(value = "修改宾客")
    @PutMapping("update")
    @Transactional
    public ResultVO updateGuestUser(@RequestBody Guest guest) {
        LambdaQueryWrapper<Guest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Guest::getId, guest.getId());
        guest.setUpdateTime(LocalDateTime.now());
        return ResultVO.okResult(guestService.update(guest, wrapper));
    }

    @ApiOperation(value = "回礼宾客")
    @PutMapping("modify")
    @Transactional
    public ResultVO recompenseGuestUser(@RequestBody GuestDTO guestDTO) {
        Guest guest = new Guest();
        LambdaQueryWrapper<Guest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Guest::getId, guestDTO.getId());
        guest.setId(guestDTO.getId());
        guest.setUpdateTime(LocalDateTime.now());
        guest.setIsRecompense(true);

        //添加一条回礼记录
        FeastRecompense recompense = new FeastRecompense();
        Guest one = guestService.getOne(wrapper);
        recompense.setAddress(one.getAddress());
        recompense.setName(one.getName());
        recompense.setCreateTime(LocalDateTime.now());
        recompense.setRecompense(guestDTO.getRecompense());
        recompenseService.save(recompense);
        return ResultVO.okResult(guestService.update(guest, wrapper));
    }

    @ApiOperation(value = "删除宾客")
    @PostMapping("delete")
    public ResultVO deleteGuestUser(@RequestBody List<String> ids) {
        guestService.removeByIds(ids);
        return ResultVO.okResult();
    }

    @ApiOperation("导出Excel")
    @PostMapping("outputExcel")
    public void showAll(HttpServletResponse response, @RequestBody Map<String, Object> map) {
        List<GuestDTO> dtoList = new ArrayList<>();
        GuestDTO guestDTO = JSON.parseObject(JSON.toJSONString(map.get("filters")), GuestDTO.class);
        Guest guest = new Guest();
        GuestDTO gDTO;
        for (Map<String, Object> m : potoToDto(guest, guestDTO)) {
            gDTO = new GuestDTO();
            gDTO.setName(Convert.toStr(m.get("name")));
            gDTO.setAddress(Convert.toStr(m.get("address")));
            gDTO.setGift(Convert.toDouble(m.get("gift")));
            gDTO.setGifts(Convert.toStr(m.get("gifts")));
            gDTO.setRemarks(Convert.toStr(m.get("remarks")));
            gDTO.setCreateTime(Convert.toDate(m.get("createTime")));
//            gDTO.setCreateTime(Convert.toLocalDateTime(m.get("createTime")));
            dtoList.add(gDTO);
        }

        String fileName = "feast" + ".xls";
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;Filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        try {
            //阿里EasyExcel
            EasyExcel.write(response.getOutputStream(), GuestDTO.class).sheet("写入").doWrite(dtoList);
        } catch (IOException e) {
            log.error("导出错误", e);
        }
    }

    private List<Map<String, Object>> potoToDto(Guest guest, GuestDTO guestDTO) {
        if (StringUtils.isNotBlank(guestDTO.getName())
                ||StringUtils.isNotBlank(guestDTO.getAddress())
                ||StringUtils.isNotBlank(guestDTO.getFeastTypeId())) {
            guest.setName(guestDTO.getName());
            guest.setAddress(guestDTO.getAddress());
            guest.setFeastTypeId(guestDTO.getFeastTypeId());
        }
        List<Map<String, Object>> list = guestService.getAll(guest);
        List<Map<String, Object>> collect;
        if (StringUtils.isNotBlank(guestDTO.getFiled()) && StringUtils.isNotBlank(guestDTO.getOrderBy())) {
            if (StringUtils.equals(guestDTO.getOrderBy(), CommonConstant.ASC)) {
                collect = list.stream().sorted(Comparator.comparing((Map<String, Object> m) -> ((double) m.get("gift")))).collect(Collectors.toList());
            } else {
                collect = list.stream().sorted(Comparator.comparing((Map<String, Object> m) -> ((double) m.get("gift"))).reversed()).collect(Collectors.toList());
            }
        }else {
            collect = list;
        }
        return collect;
    }
}
